package com.xinz.srmi;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.xinz.srmi.impl.SimpleHttpClient;
import com.xinz.srmi.impl.SimpleSocketClient;

public abstract class SrmiClient extends Thread implements InvokeConnector{
	/***/
	protected RemoteInvoker remoteInvoker;
	protected NativeInvoker nativeInvoker;
	protected Session session;
	@Override
	public Session getSession() {
		return session;
	}
	
	public static SrmiClient createHttp(String url,ConfigFactory foctroy){
		try {
			return new SimpleHttpClient(new URL(url), foctroy);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static SrmiClient createSocket(String ip,int port,ConfigFactory foctroy){
		try {
			return new SimpleSocketClient(ip,port,foctroy);
		} catch (IOException e) { 
			e.printStackTrace();
		}
		return null;
	}
	
	
	/***
	 * 连接到远程服务器
	 */
	public synchronized void connect() {
		start();
	}
	/**
	 * 获取远程实现
	 * @param clazz
	 * @return
	 */
	public <T> T getImplement(Class<T> clazz){
		return remoteInvoker.getImplement(clazz);
	}
	
	protected SrmiClient(ConfigFactory foctyoy){
		session = new Session(new NativeInterfaceProvider());
		remoteInvoker = new RemoteInvoker(foctyoy, this);
		session.initInvoker(remoteInvoker);
		nativeInvoker = new NativeInvoker(foctyoy);
	}
	
	
	@Override
	public abstract Buffer request(Buffer request)throws IOException;

}
